package openadmin.web;

import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.faces.application.Application;
import javax.faces.bean.*;
import java.io.Serializable;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.component.html.HtmlPanelGrid;
import javax.faces.context.FacesContext;

import openadmin.dao.Base;
import openadmin.dao.exception.DataException;
import openadmin.dao.operation.DaoJpaHibernate;
import openadmin.dao.operation.DaoOperationFacade;
import openadmin.dao.operation.LogDao;
import openadmin.dao.operation.LogOperationFacade;
import openadmin.model.control.User;


@ManagedBean
public class LoginAction implements Serializable{
 

	@ManagedProperty(value="#{user}")
	private User user;
	
	private FacesContext context = FacesContext.getCurrentInstance();
	
	/** Field that contain the working language*/
	private ResourceBundle language = ResourceBundle.getBundle("messagesview");	
	
	private HtmlPanelGrid grid; 
	
	public String execute() throws DataException, NoSuchAlgorithmException{
		
		String result = "No existeix";
		
		String page = "login";


		//Connection database 
		DaoOperationFacade clientLog = new DaoJpaHibernate(user, "log_post", null);	
		LogOperationFacade log = new LogDao(clientLog, "clientweb");
		DaoOperationFacade conn = new DaoJpaHibernate(user, "ayto_post", log);
		
		   	 
		/**Field that contain one list of Base objects */
		List <Base> listUsers = conn.findObjects(user);	
		
		if (conn.isResultOperation()){
			
			user = (User)listUsers.get(0);	    
		
			//Locale default user
			clientLog.setUser(user);
			conn.setUser(user);
			 
			Locale locale = new Locale (user.getLanguage());
			context.getViewRoot().setLocale(locale);
			language = ResourceBundle.getBundle("messagesview", locale);	
			
			result = "existeix";
			page = "home";
		  
		} 
		  

		conn.finalize();
		log.finalizeLog();  
		
		
		grid.getChildren().clear();
		Application app = context.getApplication();
		HtmlOutputText outText = (HtmlOutputText) app.createComponent(HtmlOutputText.COMPONENT_TYPE);
		 

		outText.setValue("Usuari: " + user.getDescription() + " " + result);
	    grid.getChildren().add(outText);
	    
	    return page;
	    		
	}
	
	public User getUser() {
		return user;
	}
	
	public void setUser(User user) {
		this.user = user;
	}
	
	public void setPanel(UIComponent component) {
	    this.grid = (HtmlPanelGrid) component;
	  }
	
	public HtmlPanelGrid getPanel() {

		if (grid == null) {
	     
			Application app = context.getApplication();
			grid = (HtmlPanelGrid) app.createComponent(HtmlPanelGrid.COMPONENT_TYPE);
	     
	    }

	    return grid;
	}
}
